import os
import django
from django_pandas.io import read_frame
from product.models import BasicProductInfo, ProductsInventory
from events.models import StoreSalesOrder, StoreSalesOrderDetail
from concurrent.futures import ThreadPoolExecutor
from django.utils import timezone  # 缺少这个导入
from datetime import timedelta     # 缺少这个导入

# 设置 Django 环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'RetailSimulator.settings')
django.setup()

class ReadFrame:
    def __init__(self, model):
        self.model = model

    def get_qs(self, *args):
        if args:
            return self.model.objects.value(*args)
        return self.model.objects.all()

    def read(self, *args):
       qs = self.get_qs(*args)
       df = read_frame(qs)
       return df

def get_product():
    rf = ReadFrame(BasicProductInfo)
    return rf.read()

def get_inventory():
    rf = ReadFrame(ProductsInventory)
    return rf.read()

def get_inventory_filter(product_codes):
    """
    根据商品代码列表获取库存信息
    :param product_codes: 商品代码列表
    :return: DataFrame 包含过滤后的库存信息
    """
    try:
        # 使用 filter 过滤指定商品代码的库存记录
        qs = ProductsInventory.objects.filter(product_code__in=product_codes)
        
        # 转换为 DataFrame
        df = read_frame(qs)
        return df
    except Exception as e:
        print(f"获取库存数据失败: {str(e)}")
        return None

def get_order(*args, days=90, **filters):
    """
    获取订单数据
    :param args: 需要查询的字段
    :param days: 查询近几天的数据，默认90天
    :param filters: 其他过滤条件
    """
    try:
        three_months_ago = timezone.now() - timedelta(days=days)
        
        # 合并过滤条件
        filters.update({'order_date__gte': three_months_ago})
        
        # 查询主表
        orders = StoreSalesOrder.objects.filter(**filters)
        if args:
            orders = orders.values(*args)
        return orders
    except Exception as e:
        logger.error(f"获取订单数据失败: {str(e)}")
        return None

def get_order_detail(*args):
    """
    获取订单明细数据
    :param args: 需要查询的字段
    """
    try:
        # 获取订单主表数据
        orders = get_order('order_id', 'order_date')
        if not orders:
            return None
            
        # 获取订单明细数据
        details = StoreSalesOrderDetail.objects.filter(
            order_id__in=[order['order_id'] for order in orders]
        )
        if args:
            details = details.values(*args)
        else:
            details = details.all()
            
        # 转换为DataFrame
        details_df = read_frame(details)
        
        # 将订单主表数据转换为DataFrame并合并
        orders_df = read_frame(orders)
        merged_df = details_df.merge(
            orders_df,
            on='order_id',
            how='left'
        )
            
        return merged_df
    except Exception as e:
        logger.error(f"获取订单明细数据失败: {str(e)}")
        return None








class WriteFrame:
    def __init__(self, objects):
        self.objects = objects

    def thread_insert(self, thread_count=4):
        """
        多线程批量生成并插入商品数据
        :param thread_count: 线程数量
        """
        batch_size = self.objects.count // thread_count
        remaining = self.objects.count % thread_count

        with ThreadPoolExecutor(max_workers=thread_count) as executor:
            futures = [
                executor.submit(self.objects.batch_insert, batch_size)
                for _ in range(thread_count)
            ]

            if remaining > 0:
                futures.append(executor.submit(self.objects.batch_insert, remaining))

            total_inserted = sum(future.result() for future in futures)

        return total_inserted